from http import HTTPStatus

from errors import Duplicate, Missing, ParkingUnavailable
from flask import Blueprint, jsonify, request
from service import client_parkings as service

bp = Blueprint("client_parkings", __name__, url_prefix="/client_parkings")


@bp.route("/", methods=["POST"])
def create_client_parking_route():
    """Создать запись о парковке клиента

    Examples:
        curl -X POST -H "Content-Type: application/json" \
        --data '{"client_id": 1, "parking_id": 1}' \
             http://127.0.0.1:8000/client_parkings/
    """
    client_id = request.json.get("client_id", None)
    parking_id = request.json.get("parking_id", None)

    if not client_id or not parking_id:
        return (
            jsonify({"error": "client_id and parking_id fields are required"}),
            HTTPStatus.BAD_REQUEST,
        )

    try:
        client_parking = service.park_client(client_id, parking_id)
    except Missing as ex:
        return jsonify({"error": ex.msg}), HTTPStatus.NOT_FOUND
    except ParkingUnavailable as ex:
        return jsonify({"error": ex.msg}), HTTPStatus.BAD_REQUEST
    except Duplicate as ex:
        return jsonify({"error": ex.msg}), HTTPStatus.BAD_REQUEST

    return jsonify(client_parking), HTTPStatus.CREATED


@bp.route("/", methods=["DELETE"])
def finish_client_parking_route():
    """
    Завершает парковку клиента – выезд с парковки (количество свободных мест увеличивается,
    проставляем время выезда). В теле запроса передать client_id, parking_id.

    Фактически, запись о парковке из таблицы не удаляется!

    Examples:
        curl -X DELETE -H "Content-Type: application/json" \
        --data '{"client_id": 1, "parking_id": 1}' \
             http://127.0.0.1:8000/client_parkings/
    """
    ...
    client_id = request.json.get("client_id", None)
    parking_id = request.json.get("parking_id", None)

    if client_id is None or parking_id is None:
        return (
            jsonify({"error": "client_id and parking_id fields are required"}),
            HTTPStatus.BAD_REQUEST,
        )

    try:
        service.end_parking(client_id, parking_id)
    except Missing as ex:
        return jsonify({"error": ex.msg}), HTTPStatus.NOT_FOUND

    return jsonify({}), HTTPStatus.NO_CONTENT
